<template>
    <div class="search">
        <a-input
            v-model:value="searchData.search"
            placeholder="搜索名字或者描述"
            style="width: 200px; color: gray; margin-left: 50px;"
            size="large"
            load
        />
        <div style="color: grey; font-size: large; margin-left: 50px; margin-top: 10px;">创建日期：</div>
        <a-range-picker v-model:value="dateRange" show-time style="margin-left: 10px;" />
        <div style="color: grey; font-size: large; margin-left: 50px; margin-top: 10px;">排序项：</div>
        <a-select
            v-model:value="searchData.order"
            placeholder="选择排序项"
            :options="ordersAll"
            style="width: 200px; margin-left: 10px;"
        />
        <a-radio-group v-model:value="searchData.orderType" style="margin-left: 20px;">
            <a-radio style=" display: flex;" value="asc">正序</a-radio>
            <a-radio style=" display: flex;" value="desc">倒序</a-radio>
        </a-radio-group>
        <a-button size="large" style="margin-left: 50px;" @click="search(1)">搜索</a-button>
    </div>
    <a-list item-layout="vertical" size="large" :pagination="pagination" :data-source="listData" style="margin-top: 20px;">
        <template #renderItem="{ item }">
            <a-list-item key="item.title">
            <template #actions>
                <span>
                    <div @click="handleLikeOrDisLike(item.id, item.index, item.isLiked)">
                        <component v-if="item.isLiked" :is="LikeTwoTone" style="margin-right: 8px" two-tone-color="#eb2f96"/>
                        <component v-else :is="LikeTwoTone" style="margin-right: 8px" two-tone-color=""/>
                        {{ item.likeCount }}
                    </div>
                </span>
                <span>
                    <div @click="handleCollectOrCancel(item.id, item.index, item.isCollected)">
                        <component v-if="item.isCollected" :is="StarTwoTone" style="margin-right: 8px" two-tone-color="#eb2f96"/>
                        <component v-else :is="StarTwoTone" style="margin-right: 8px" />
                        {{ item.collectCount }}
                    </div>
                </span>
            </template>
            <template #extra>
                <span v-for="{ icon, text } in item.actions" :key="icon">
                    <div @click="handleActionClick(text, item.id, item.title, item.isLocked)">
                        <component :is="icon" style="margin-right: 8px" />
                        {{ text }}
                    </div>
                </span>
            </template>
            <a-list-item-meta :description="item.description">
                <template #title>
                    <a>{{ item.title }}</a>
                </template>
            </a-list-item-meta>
            </a-list-item>
        </template>
    </a-list>
</template>

<script lang="ts">
export default {
    name: 'TopicList'
}
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import type { Dayjs } from 'dayjs';
import { searchTopicList, likeTopic, disLikeTopic, collectTopic, cancelCollectTopic, lockTopic, unlockTopic, deleteTopic } from '@/api/forum_api'
import { DeleteOutlined, EnterOutlined, LockOutlined, UnlockOutlined, UserOutlined, LikeTwoTone, StarTwoTone } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import router from '@/router';

const listData =  ref<Record<string, any>[]>([]);
interface SearchData {
    search: string,
    created: boolean,
    collected: boolean 
    beginTime: any,
    EndTime: any,
    order: string,
    orderType: string
}
const searchData = reactive<SearchData>({
  search: '',
  created: false,
  collected: false,
  beginTime: null,
  EndTime: null,
  order: 'likeCount',
  orderType: 'desc'
})
type RangeValue = [Dayjs, Dayjs];
const dateRange = ref<RangeValue>();
const ordersAll = ref<{label: string, value: string, disabled: boolean}[]>([
{label: '创建时间', value: 'gmtCreated', disabled: false},
{label: '点赞数', value: 'likeCount', disabled: false},
{label: '收藏数', value: 'collectCount', disabled: false}
])
const pagination = {
    onChange: (page: number) => {
        pagination.current = page
        search(page)
    },
    current: 1,
    pageSize: 5,
    total: 0,
};
const props = defineProps(['id'])

onMounted(async () => {
    await search(1)
});
const search = async (page:number) => {
    if (dateRange.value != undefined && dateRange.value.length == 2) {
        searchData.beginTime = dateRange.value?.[0].format('YYYY-MM-DD HH:mm:ss')
        searchData.EndTime = dateRange.value?.[1].format('YYYY-MM-DD HH:mm:ss')
    }
    if (props.id === 'collected') {
        searchData.collected = true
    } else if (props.id === 'created') {
        searchData.created = true
    }
    await searchTopicList(searchData, page, 5)
    .then(resp => {
        pagination.total = resp.data.total
        listData.value = []
        for (let i = 0; i < resp.data.list.length; i++) {
            let data = {
                index: i,
                title: resp.data.list[i].topic,
                description: resp.data.list[i].creatorName,
                id: resp.data.list[i].id,
                likeCount: resp.data.list[i].likeCount,
                collectCount: resp.data.list[i].collectCount,
                isLiked: resp.data.list[i].isLiked,
                isCollected: resp.data.list[i].isCollected,
                isLocked: resp.data.list[i].isLocked,
                actions: [{}],
            }
            if (resp.data.list[i].isCreator === true) {
                data.actions.push({ icon: EnterOutlined, text: '进入' })
                if (resp.data.list[i].isLocked === 'N') {
                    data.actions.push({ icon: LockOutlined, text: '禁用' })
                } else {
                    data.actions.push({ icon: UnlockOutlined, text: '解禁' })
                }
                data.actions.push({ icon: DeleteOutlined, text: '删除' })
            }  else {
                data.actions.push({ icon: EnterOutlined, text: '进入' })
            }
            listData.value.push(data)
        }
        searchData.search = ""
        searchData.beginTime = null
        searchData.EndTime = null
        dateRange.value = undefined;
    })
    .catch(error => {})
};
const handleActionClick = (text:string, id:number, name:string, isLocked: string) => {
    switch (text) {
        case "进入":
            handleTopicEnter(id, name, isLocked)
            break
        case "禁用":
            handleTopicLock(id)
            break
        case "解禁":
            handleTopicUnLock(id)
            break
        case "删除":
            handleTopicDelete(id)
            break
    }
}
const handleTopicEnter = (id:number, name:string, isLock: string) => {
    router.push({name: 'topicDetail', params:{topicId: id, title: name, isLocked: isLock}})
}
const handleTopicLock = async (id:number) => {
    await lockTopic(id)
    .then(resp => {
        message.info("锁定成功")
        search(pagination.current)
    })
    .catch(err => {})
}
const handleTopicUnLock = async (id:number) => {
    await unlockTopic(id)
    .then(resp => {
        message.info("解锁成功")
        search(pagination.current)
    })
    .catch(err => {})
}
const handleTopicDelete = async (id:number) => {
    await deleteTopic(id)
    .then(resp => {
        message.info("删除成功")
        search(pagination.current)
    })
    .catch(err => {})
}
const handleLikeOrDisLike = async (id:number, index:number, isLiked:boolean) => {
    if (isLiked) {
        await disLikeTopic(id)
        .then(resp => {
            listData.value[index].likeCount -= 1
            message.info("取消成功!")
        })
        .catch(err => {})
    } else {
        await likeTopic(id)
        .then(resp => {
            listData.value[index].likeCount += 1
            message.info("点赞爆棚！")
        })
        .catch(err => {})
    }
    listData.value[index].isLiked = !listData.value[index].isLiked
};
const handleCollectOrCancel = async (id:number, index:number, isCollected:boolean) => {
    if (isCollected) {
        await cancelCollectTopic(id)
        .then(resp => {
            listData.value[index].collectCount -= 1
            message.info("取消成功!")
        })
        .catch(err => {})
    } else {
        await collectTopic(id)
        .then(resp => {
            listData.value[index].collectCount += 1
            message.info("收藏成功！")
        })
        .catch(err => {})
    }
    listData.value[index].isCollected = !listData.value[index].isCollected
}

</script>

<style scoped>
.search {
  display: flex;
  margin-top: 20px;
}
</style>